package com.blockchain.front.service.financial.achieve;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.xml.bind.DatatypeConverter;

import com.blockchain.common.enums.CoinType;
import com.blockchain.common.enums.EtherenumAppleTpye;
import com.blockchain.common.enums.IsPass;
import com.blockchain.common.enums.XlbType;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.exception.LogicalException;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.framework.service.query.ItemParser;
import com.blockchain.front.service.financial.QbManage;
import com.blockchain.front.service.financial.entity.AccountEntity;
import com.blockchain.front.service.financial.entity.BTCMessage;
import com.blockchain.front.service.financial.entity.Balance;
import com.blockchain.front.service.financial.entity.Jyjl;
import com.blockchain.front.service.financial.entity.Payments;
import com.blockchain.front.util.JsonUtil;
import com.blockchain.util.HttpRequest;
import com.blockchain.util.MyCrypt;
import com.blockchain.util.StringHelper;
import com.blockchain.variables.P2PConst;

import net.sf.json.JSONObject;

public class QbManageImpl extends AbstractFinanciaService implements QbManage {

	public static class QbManageFactory implements ServiceFactory<QbManage> {

		@Override
		public QbManage newInstance(ServiceResource serviceResource) {
			return new QbManageImpl(serviceResource);
		}
	}

	public QbManageImpl(ServiceResource serviceResource) {
		super(serviceResource);
	}

	@Override
	public String addQbdz(int bid) throws Throwable {
		if (bid <= 0) {
			throw new LogicalException("币不存在。");
		}
		String qbdz = "";
		// String jc = selectString(P2PConst.DB_USER, "SELECT F03 FROM T6013
		// WHERE F01=?", bid);// 简介
		// String coinType = selectString(P2PConst.DB_USER, "SELECT F26 FROM
		// T6013 WHERE F01=?", bid);// 简介
		// if ("SWT".equals(jc)) {
		// qbdz = swt(bid, jc);
		// }
		// if ("DOGE".equals(jc) || "LTC".equals(jc) || "BTC".equals(jc) ||
		// "PPC".equals(jc)) {
		// qbdz = btc(bid, jc);
		// }
		// if (CoinType.ETH.name().equals(coinType)) {
		// String bjc = selectString(P2PConst.DB_USER, "SELECT F02 FROM T6013
		// WHERE F01=?", bid);
		// qbdz = eth(bid, bjc);
		// }
		// if("TCC".equals(jc)){
		// qbdz = tcc(bid, jc);
		// }
		// return qbdz;

		String jc = selectString(P2PConst.DB_USER, "SELECT F02 FROM T6013 WHERE F01=?", bid);// 简介
		String coinType = selectString(P2PConst.DB_USER, "SELECT F26 FROM T6013 WHERE F01=?", bid);// 简介
		if (CoinType.ETH.name().equals(coinType)) {
			qbdz = eth(bid, jc);
		} else if (CoinType.SWT.name().equals(coinType) && jc != null) {
			if ("TCC".equals(jc.toUpperCase())) {
				qbdz = tcc(bid, jc);
			} else {
				qbdz = swt(bid, jc);
			}
		} else if (CoinType.NEO.name().equals(coinType)) {
			qbdz = neo(bid, jc);
		} else {
			qbdz = btc(bid, jc);
		}

		return qbdz;

	}

	/**
	 * 
	 * @param userid
	 * @throws Exception
	 * @创建比特系列钱包地址 2017年8月9日16:20:50 getaddressesbyaccount 判断是否已经存在方法。
	 */
	private String btc(int bid, String jc) throws Exception {
		String qbdz = "";
		String T6012_ = "T6012_" + jc;
		int accountId = serviceResource.getSession().getAccountId();
		String username = selectString(P2PConst.DB_USER, "SELECT F02 FROM T6010 WHERE F01=?", accountId);
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT F03 FROM ").append(T6012_).append(" AS T6");
		sql.append(" WHERE T6.F02=? AND T6.F05=?");
		qbdz = selectString(P2PConst.DB_USER, sql.toString(), accountId, IsPass.F);
		if (StringHelper.isEmpty(qbdz)) {
			String s = post("getnewaddress", "[\"" + username + "\"]", bid);
			Map<String, Object> reault_map = JsonUtil.GsonToMaps(s);
			if (reault_map.get("result") != null && !StringHelper.isEmpty(reault_map.get("result").toString())) {
				String address = reault_map.get("result").toString();
				execute(getConnection(P2PConst.DB_USER),
						"INSERT INTO " + T6012_
								+ " SET F02=?,F03=?,F04=?,F05=?,F06=CURRENT_TIMESTAMP(),F07=DATE_ADD(NOW(),INTERVAL 1 YEAR)",
						accountId, address, null, IsPass.F);
			}
		}
		qbdz = selectString(P2PConst.DB_USER, sql.toString(), accountId, IsPass.F);
		return qbdz;
	}

	/**
	 * 
	 * @param userid
	 * @throws Exception
	 * @创建小蚁列钱包地址
	 */
	private String neo(int bid, String jc) throws Exception {
		String qbdz = "";
		String T6012_ = "T6012_" + jc;

		int accountId = serviceResource.getSession().getAccountId();
		String ip = selectString(P2PConst.DB_USER, "SELECT F18 FROM T6013 WHERE F01=?", bid);// IP
		String port = selectString(P2PConst.DB_USER, "SELECT F19 FROM T6013 WHERE F01=?", bid);// PORT
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT F03 FROM ").append(T6012_).append(" AS T6");
		sql.append(" WHERE T6.F02=? AND T6.F05=?");
		System.out.println(sql.toString());
		qbdz = selectString(P2PConst.DB_USER, sql.toString(), accountId, IsPass.F);

		if (StringHelper.isEmpty(qbdz)) {
			StringBuffer url = new StringBuffer(ip).append(":" + port);
			HashMap<String, Object> map = new HashMap<String, Object>();
			UUID uuid = UUID.randomUUID();
			String password = uuid.toString();// 使用UUID来作为随机密码
			password = password.replace("-", "");
			map.put("jsonrpc", "2.0");
			map.put("method", "getnewaddress");
			map.put("id", "1");
			map.put("params", new String[] { password });

			String result = HttpRequest.sendPost(url.toString(), JsonUtil.GsonString(map), CoinType.ETH.getName());
			Map<String, Object> reault_map = JsonUtil.GsonToMaps(result);
			String address = reault_map.get("result").toString();
			if (!StringHelper.isEmpty(address)) {
				execute(getConnection(P2PConst.DB_USER),
						"INSERT INTO " + T6012_
								+ " SET F02=?,F03=?,F04=?,F05=?,F06=CURRENT_TIMESTAMP(),F07=DATE_ADD(NOW(),INTERVAL 1 YEAR)",
						accountId, address, password, IsPass.F);
			}
		}
		qbdz = selectString(P2PConst.DB_USER, sql.toString(), accountId, IsPass.F);
		return qbdz;
	}

	private String post(String method, String condition, int bid) throws Exception {
		authenticator(bid);
		BTCMessage b = get(bid);
		String result = "";
		String tonce = "" + (System.currentTimeMillis() * 1000);
		String url = "http://" + b.ACCESS_KEY + ":" + b.SECRET_KEY + "@" + b.IP + ":" + b.PORT;
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		String userpass = b.ACCESS_KEY;
		String basicAuth = "Basic" + DatatypeConverter.printBase64Binary(userpass.getBytes());
		con.setRequestMethod("POST");
		con.setRequestProperty("Json-Rpc-Tonce", tonce.toString());
		con.setRequestProperty("Authorization", basicAuth);
		String postdata = "{\"method\":\"" + method + "\", \"params\":" + condition + "}";
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(postdata);
		wr.flush();
		wr.close();
		int responseCode = con.getResponseCode();
		if (responseCode != 200) {
			return "{\"result\":null,\"error\":" + responseCode + "}";
		}
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
		inputLine = in.readLine();
		response.append(inputLine);
		in.close();
		result = response.toString();
		System.out.println(result + "创建比特系列钱包返回信息");
		return result;
	}

	/**
	 * 
	 * @param bid
	 * @查询币信息
	 * @throws SQLException
	 *             2017年8月9日16:21:02
	 */
	private BTCMessage get(int bid) throws SQLException {
		return select(getConnection(P2PConst.DB_USER), new ItemParser<BTCMessage>() {

			@Override
			public BTCMessage parse(ResultSet re) throws SQLException {
				BTCMessage x = new BTCMessage();
				while (re.next()) {
					x.IP = re.getString(1);
					x.PORT = re.getString(2);
					x.ACCESS_KEY = re.getString(3);
					x.SECRET_KEY = re.getString(4);
					x.SHORTNAME = re.getString(5);
				}
				return x;
			}
		}, "SELECT F18,F19,F20,F21,F03 FROM T6013 WHERE F01=?", bid);

	}

	/**
	 * 
	 * @throws SQLException
	 * @创建RPC链接 2017年8月9日16:21:13
	 */
	private void authenticator(final int bid) throws SQLException {
		Authenticator.setDefault(new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				BTCMessage b = null;
				try {
					b = get(bid);
				} catch (SQLException e) {
					e.printStackTrace();
					System.out.printf("创建钱包地址失败,返回结果：%s", e.getMessage());
				}
				return new PasswordAuthentication(b.ACCESS_KEY, b.SECRET_KEY.toCharArray());
			}
		});
	}

	/**
	 * 
	 * @param bid
	 * @创建井通钱包地址
	 * @throws SQLException
	 * 
	 */
	private String swt(int bid, String jc) throws SQLException {
		int accountId = serviceResource.getSession().getAccountId();
		String qbdz = "";
		String ip = selectString(P2PConst.DB_USER, "SELECT F18 FROM T6013 WHERE F01=?", bid);// IP
		if (!StringHelper.isEmpty(jc) && !StringHelper.isEmpty(ip)) {
			String T6012_ = "T6012_" + jc;
			StringBuffer s = new StringBuffer();
			s.append("SELECT F03 FROM ").append(T6012_).append(" AS T6");
			s.append(" WHERE T6.F02=? AND T6.F05=?");
			qbdz = selectString(P2PConst.DB_USER, s.toString(), accountId, IsPass.F);
			if (StringHelper.isEmpty(qbdz)) {
				StringBuffer url = new StringBuffer(ip).append("/v1/wallet/new");
				String result = HttpRequest.sendGet(url.toString());
				Map<String, Object> reault_map = JsonUtil.GsonToMaps(result);
				if (reault_map != null && reault_map.get("success") != null
						&& !StringHelper.isEmpty(reault_map.get("success").toString())
						&& Boolean.parseBoolean(reault_map.get("success").toString())) {
					try {
						Map<String, String> wallet = (Map<String, String>) reault_map.get("wallet");
						String address = wallet.get("address");// 井通钱包地址
						String secret = wallet.get("secret");// 井通钱包私钥
						if (!StringHelper.isEmpty(address) && !StringHelper.isEmpty(secret)) {
							String jm = MyCrypt.myEncode(secret);
							execute(getConnection(P2PConst.DB_USER),
									"INSERT INTO " + T6012_
											+ " SET F02=?,F03=?,F04=?,F05=?,F06=CURRENT_TIMESTAMP(),F07=DATE_ADD(NOW(),INTERVAL 1 YEAR)",
									accountId, address, jm, IsPass.F);
						}
					} catch (Exception e) {
						System.out.printf("创建井通钱包地址失败,返回结果：%s", result);
					}

				}
				qbdz = selectString(P2PConst.DB_USER, s.toString(), accountId, IsPass.F);
			}
		}
		return qbdz;
	}

	/**
	 * 
	 * @param userid
	 * @throws Exception
	 * @创建以太坊列钱包地址
	 */
	private String eth(int bid, String jc) throws Exception {
		String qbdz = "";
		String T6012_ = "T6012_" + jc;
		int accountId = serviceResource.getSession().getAccountId();
		String ip = selectString(P2PConst.DB_USER, "SELECT F18 FROM T6013 WHERE F01=?", bid);// IP
		String port = selectString(P2PConst.DB_USER, "SELECT F19 FROM T6013 WHERE F01=?", bid);// PORT
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT F03 FROM ").append(T6012_).append(" AS T6");
		sql.append(" WHERE T6.F02=? AND T6.F05=?");
		System.out.println(sql.toString());
		qbdz = selectString(P2PConst.DB_USER, sql.toString(), accountId, IsPass.F);

		if (StringHelper.isEmpty(qbdz)) {
			StringBuffer url = new StringBuffer(ip).append(":" + port);
			HashMap<String, Object> map = new HashMap<String, Object>();
			UUID uuid = UUID.randomUUID();
			String password = uuid.toString();// 使用UUID来作为随机密码
			password = password.replace("-", "");
			map.put("jsonrpc", "2.0");
			map.put("method", "personal_newAccount");
			map.put("id", "1");
			map.put("params", new String[] { password });

			String result = HttpRequest.sendPost(url.toString(), JsonUtil.GsonString(map), CoinType.ETH.getName());
			Map<String, Object> reault_map = JsonUtil.GsonToMaps(result);
			String address = reault_map.get("result").toString();
			if (!StringHelper.isEmpty(address)) {
				execute(getConnection(P2PConst.DB_USER),
						"INSERT INTO " + T6012_
								+ " SET F02=?,F03=?,F04=?,F05=?,F06=CURRENT_TIMESTAMP(),F07=DATE_ADD(NOW(),INTERVAL 1 YEAR)",
						accountId, address, password, IsPass.F);
			}
		}
		qbdz = selectString(P2PConst.DB_USER, sql.toString(), accountId, IsPass.F);
		return qbdz;
	}

	@Override
	public String tcc(int bid, String bjc) throws Throwable {
		int accountId = serviceResource.getSession().getAccountId();
		String r_address = selectString(P2PConst.DB_USER, "SELECT F12 FROM T6013 WHERE F01=?", bid);// 热钱包地址
		String r_secret = selectString(P2PConst.DB_USER, "SELECT F13 FROM T6013 WHERE F01=?", bid);// 热钱包私钥
		String qbdz = "";
		String ip = selectString(P2PConst.DB_USER, "SELECT F18 FROM T6013 WHERE F01=?", bid);// IP
		if (!StringHelper.isEmpty(bjc) && !StringHelper.isEmpty(ip)) {
			String T6012_ = "T6012_" + bjc;
			StringBuffer s = new StringBuffer();
			s.append("SELECT F03 FROM ").append(T6012_).append(" AS T6");
			s.append(" WHERE T6.F02=? AND T6.F05=?");
			qbdz = selectString(P2PConst.DB_USER, s.toString(), accountId, IsPass.F);// 判断钱包地址是否存在。
			if (StringHelper.isEmpty(qbdz) && !StringHelper.isEmpty(r_address) && !StringHelper.isEmpty(r_secret)) {
				Map<String, Object> wallet = swt(ip);// 创建TCC钱包地址
				String address = wallet.get("address").toString();// TCC钱包地址
				String secret = wallet.get("secret").toString();// TCC私钥
				if (!StringHelper.isEmpty(address) && !StringHelper.isEmpty(secret)) {
					BigDecimal ye = accountBig(ip, r_address, "SWT");// 获取热钱包余额
					if (ye.compareTo(new BigDecimal(25)) > 0) {
						String res = zr(ip, r_address, r_secret, new BigDecimal(26), "SWT", address);// 激活钱包
						JSONObject jsonObject = JSONObject.fromObject(res);
						System.out.println(res);
						boolean success = jsonObject.getBoolean("success");
						String hash = "";
						if (success) {
							hash = jsonObject.getString("hash");
						}
						String jm = MyCrypt.myEncode(secret);// 激活成功保存地址
						execute(getConnection(P2PConst.DB_USER),
								"INSERT INTO " + T6012_
										+ " SET F02=?,F03=?,F04=?,F05=?,F06=CURRENT_TIMESTAMP(),F07=DATE_ADD(NOW(),INTERVAL 1 YEAR)",
								accountId, address, jm, IsPass.F);

						execute(getConnection(P2PConst.DB_USER),
								"INSERT INTO  T6061 SET F02=?,F03=?,F04=25,F05=?,F06=CURRENT_TIMESTAMP(),F07=?,F10=?", // 记录激活费用。
								accountId, address, hash, EtherenumAppleTpye.CG, bid);
					}
				}
				qbdz = selectString(P2PConst.DB_USER, s.toString(), accountId, IsPass.F);
			}
		}
		return qbdz;
	}

	@Override
	public Map<String, Object> swt(String ip) throws Throwable {
		Map<String, Object> wallet = null;
		StringBuffer url = new StringBuffer(ip).append("/v1/wallet/new");
		String result = HttpRequest.sendGet(url.toString());
		Map<String, Object> reault_map = JsonUtil.GsonToMaps(result);
		if (reault_map != null && reault_map.get("success") != null
				&& !StringHelper.isEmpty(reault_map.get("success").toString())
				&& Boolean.parseBoolean(reault_map.get("success").toString())) {
			try {
				wallet = (Map<String, Object>) reault_map.get("wallet");
			} catch (Exception e) {
				System.out.printf("创建井通系列钱包地址失败,返回结果：%s", result);
			}
		}
		return wallet;
	}

	@Override
	public String zr(String ip, String address_z, String secret, BigDecimal amount, String bjc, String address_j)
			throws Throwable {
		String result = "";
		String KEY = MyCrypt.myDecode(secret);// 秘钥（解密）
		AccountEntity pt = account(ip, address_z, bjc);// 用户钱包信息
		if (pt.success) {
			SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddhhmmssSS");
			String id = sd.format(new Date());
			StringBuffer data = new StringBuffer();
			data.append("{");
			data.append("\"secret\":\"").append(KEY).append("\",");
			data.append("\"client_resource_id\":\"").append(id).append("\",");
			data.append("\"payment\":{");
			data.append("\"source_account\":\"").append(address_z).append("\",");
			data.append("\"source_amount\":{");
			data.append("\"value\":\"").append(pt.balances.get(0).value).append("\",");
			data.append("\"currency\":\"").append(pt.balances.get(0).currency).append("\",");
			data.append("\"issuer\":\"").append(pt.balances.get(0).counterparty).append("\"},");
			data.append("\"source_slippage\":\"").append("0").append("\",");
			data.append("\"destination_account\":\"").append(address_j).append("\",");
			data.append("\"destination_amount\":{");
			data.append("\"value\":\"").append(amount).append("\",");
			data.append("\"currency\":\"").append(pt.balances.get(0).currency).append("\",");
			data.append("\"issuer\":\"").append(pt.balances.get(0).counterparty).append("\"},");
			data.append("\"memos\":[{");
			data.append("\"memo_type\":\"").append("String").append("\",");
			data.append("\"memo_data\":\"").append("").append(id).append("\"}]");
			data.append("}");
			data.append("}");
			String url = new StringBuffer(ip).append("/v1/accounts/").append(address_z)
					.append("/payments?validated=true").toString();
			result = HttpRequest.sendPost(url, data.toString());
		}
		return result;
	}

	@Override
	public AccountEntity account(String ip, String address, String bjc) throws Throwable {
		StringBuffer u = new StringBuffer(ip).append("/v1/accounts/").append(address).append("/balances")
				.append("?currency=").append(bjc).append("&counterparty=").append("");
		String res = HttpRequest.sendGet(u.toString());// 获取井通系列钱包信息
		System.out.println(res + "获取井通系列钱包信息");
		JSONObject jsonObject = JSONObject.fromObject(res.toString());
		Map<String, Class> classMap = new HashMap<String, Class>();
		classMap.put("balances", Balance.class);
		return (AccountEntity) JSONObject.toBean(jsonObject, AccountEntity.class, classMap);
	}

	@Override
	public String bjc(int bid) throws Throwable {
		return selectString(P2PConst.DB_USER, "SELECT F03 FROM T6013 WHERE F01=?", bid);
	}

	@Override
	public String ip(int bid) throws Throwable {
		return selectString(P2PConst.DB_USER, "SELECT F18 FROM T6013 WHERE F01=?", bid);
	}

	@Override
	public BigDecimal accountBig(String ip, String address, String bjc) throws Throwable {
		StringBuffer u = new StringBuffer(ip).append("/v1/accounts/").append(address).append("/balances")
				.append("?currency=").append(bjc).append("&counterparty=").append("");
		String res = HttpRequest.sendGet(u.toString());// 获取SWT钱包信息
		System.out.println(res + "SWT钱包信息");
		JSONObject jsonObject = JSONObject.fromObject(res.toString());
		Map<String, Class> classMap = new HashMap<String, Class>();
		classMap.put("balances", Balance.class);
		AccountEntity ptzh = (AccountEntity) JSONObject.toBean(jsonObject, AccountEntity.class, classMap);
		BigDecimal ptzhze = new BigDecimal(ptzh.balances.get(0).value);
		BigDecimal ptzhdj = new BigDecimal(ptzh.balances.get(0).freezed);
		BigDecimal ye = ptzhze.subtract(ptzhdj);
		return ye;
	}

	@Override
	public void synchronization(int bid, String address, String currency) throws Throwable {
		System.out.println("查询" + currency + "交易记录start");
		int userid = serviceResource.getSession().getAccountId();
		int id = selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6025 WHERE F02=? AND F03=?  ", userid, bid);// 锁用户虚拟币账户表
		selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6025 WHERE F01=?", id);
		String ip = selectString(P2PConst.DB_USER, "SELECT F18 FROM T6013 WHERE F01=?", bid);// IP
		StringBuffer s = new StringBuffer(ip).append("/v1/accounts/").append(address).append("/payments");
		s.append("?destination_account=").append(address);
		s.append("&direction=").append("incoming");
		s.append("&exclude_failed=").append(true);
		s.append("&results_per_page=").append(100);
		s.append("&page=").append(1);
		String result = HttpRequest.sendGet(s.toString());
		System.out.println("查询SWT交易记录返回信息" + result + "用户ID" + userid);
		Jyjl jyjl = (Jyjl) JSONObject.toBean(JSONObject.fromObject(result), Jyjl.class);
		if (jyjl.success) {
			Payments[] payments = jyjl.payments;
			if (payments != null) {
				for (Payments payment : payments) {
					if (!StringHelper.isEmpty(payment.result) && payment.result.equals("tesSUCCESS")
							&& payment.amount.currency.equals(currency) && "received".equals(payment.type)) {

						serviceResource.openTransactions();
						try {
							int hxcount = selectInt(P2PConst.DB_USER, "SELECT COUNT(F02) FROM T6012_3 WHERE F02=?",
									payment.hash);// 返回哈希值是否存在
							if (hxcount == 0) {
								String bjc = payment.amount.currency;
								if (payment.amount.currency.equals("6CAB220FC47B66486AC27F3A91A0BA5A6003A860")) {
									bjc = "TCC";
								}
								int T6012_id = selectInt(P2PConst.DB_USER,
										"SELECT F01 FROM T6012_" + bjc + " WHERE F02=? AND F03=? AND F05=?", userid,
										address, IsPass.F);
								if (T6012_id > 0) {
									BigDecimal ky = new BigDecimal(payment.amount.value);
									if (ky.compareTo(new BigDecimal(0)) > 0) {
										int T6012_3id = insert(getConnection(P2PConst.DB_USER),
												"INSERT INTO T6012_3 SET F02=?,F03=CURRENT_TIMESTAMP(),F04=?,F07=?,F10=?,F11=?", // 增加swt转入记录
												payment.hash, ky, T6012_id, bid, payment.amount.value);
										execute(getConnection(P2PConst.DB_USER), "INSERT INTO T6012_4 SET F01=?,F02=?",
												T6012_3id, result);// 增加转入返回记录
										if (T6012_3id > 0 && ky.compareTo(new BigDecimal(0)) > 0) {
											execute(getConnection(P2PConst.DB_USER),
													"INSERT INTO T6025 SET F02=?,F03=?,F04=? ON DUPLICATE KEY UPDATE F02=?,F03=?,F04=F04+?",
													userid, bid, ky, userid, bid, ky);
											String bz = "交易哈希:" + payment.hash;
											execute(getConnection(P2PConst.DB_USER),
													"INSERT INTO T6026 SET F02=?,F03=?,F04=?,F05=CURRENT_TIMESTAMP(),F06=?,F07=?,F08=?",
													userid, bid, XlbType.ZR, ky, T6012_3id, bz);
											execute(getConnection(P2PConst.DB_USER),
													"INSERT INTO T6027 SET F02=?,F03=?,F04=?,F05=?,F06=?,F07=CURRENT_TIMESTAMP(),F08=?,F09=?,F10=?",
													userid, bid, ky, ky, payment.counterparty, address, IsPass.S, bz);
											System.out.println("转B到临时钱包END,转入金额：" + payment.amount.value + "可用：" + ky);
										
										} else {
											throw new ParameterException("err_1008");
										}
									}
								}
							}
						} catch (Throwable e) {
							serviceResource.rollback();
							e.printStackTrace();
							throw new LogicalException(e.getMessage());
						}
					}
				}
			}
		}
	}

	public static void main(String[] args) {

	}
}